

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

function getServerDate(){
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new window.XMLHttpRequest();
    }else{ // ie
        xhr = new ActiveObject("Microsoft")
    }

    xhr.open("GET","/",false)//false不可变
    xhr.send(null);
    var date = xhr.getResponseHeader("Date");
    return new Date(date);
}

function dateToToday(date) {
    if(date){
        var today= getServerDate();
        var time = new Date(date).getTime();

        if(time-today > 0 && (time-today)/86400000 < 30){
            return 2;
        }else if( time-today > 0 ){
            return 1;
        }else {
            return 0;
        }
    }else {
        // 没有date
        return 4;
    }

}

//更新成功提示
function updateSuccess($,layer,res) {

    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    if(JSON.stringify(res[0]) == "{}"){
        layer.msg("更新成功！",{
            icon: 1,
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        },function () {
            parent.layer.close(index);
        });
    }else {
        layer.msg("更新失败！",{
            icon: 2,
            time: 1000, //2秒关闭（如果不配置，默认是3秒）

        }, function(){
            console.log(res);
            for(var i in res[0]){

                $("[name='"+i+"']").css( "border","1px solid red");
                // 0是格式错误或者必填项没填写 2是唯一项目重复
                if(res[0][i] == 0){

                    layer.tips('填入格式错误',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});

                }else if(res[0][i] == 2){
                    layer.tips('填入内容已存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }else if(res[0][i] == 1){
                    layer.tips('不存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }
            }
        });
    }
}
//新建成功提示
function newSuccess($,layer,res) {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    console.log(res);
    if(JSON.stringify(res[0]) == "{}"){
        $(".layui-input").val("");
        layer.msg("新建成功！",{
            icon: 1,
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        },function () {
            parent.layer.close(index);
        });
    }else {
        layer.msg("新建失败！",{
            icon: 0,
            time: 1000, //2秒关闭（如果不配置，默认是3秒）

        }, function(){
            for(var i in res[0]){

                $("[name='"+i+"']").css( "border","1px solid red");
                // 0是格式错误或者必填项没填写 2是唯一项目重复
                if(res[0][i] == 0){

                    layer.tips('填入格式错误',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});

                }else if(res[0][i] == 2){
                    layer.tips('填入内容已存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }else if(res[0][i] == 1){
                    layer.tips('不存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }

            }

        });
    }
}
//成功后不关闭
function newSuccessNoClose($,layer,res) {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引

    if(JSON.stringify(res[0]) == "{}"){
        $(".layui-input").val("");
        layer.msg("新建成功！",{
            icon: 1,
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        },function () {

        });
    }else {
        layer.msg("新建失败！",{
            icon: 0,
            time: 1000, //2秒关闭（如果不配置，默认是3秒）

        }, function(){


            for(var i in res[0]){

                $("[name='"+i+"']").css( "border","1px solid red");
                // 0是格式错误或者必填项没填写 2是唯一项目重复
                if(res[0][i] == 0){

                    layer.tips('填入格式错误',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});

                }else if(res[0][i] == 2){
                    layer.tips('填入内容已存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }else if(res[0][i] == 1){
                    layer.tips('不存在',   "[name='"+i+"']", {
                        tips: [1, 'red'],
                        tipsMore: true,
                        time: 4000});
                }

            }

        });
    }
}
//filename是字段名 下载文件
function download($,layer,filename) {
    $("#"+filename+"down").on('click',function () {
        if($("#"+filename).val()){

            window.location.href = contextPath+"/files?fileid="+$("#"+filename).val();

        }else {
            layer.msg("文件没有被上传！");
        }
    });
}

function checkEndTime(startTime,endTime){


    var start = new Date(startTime.toString().replace("-", "/").replace("-", "/"));
    var end = new Date(endTime.toString().replace("-", "/").replace("-", "/"));

    if( end >= start){
        return true;
    }
    return false;

}




//单文件上传
function uploadOneFile(upload,$,layer,tablename,ownerid,filename) {



    var lookBtn = "#look"+filename+"Btn";
    var delBtn = "#del"+filename+"Btn";
    var uploadBtn = "#" +filename+"Btn";
    var fileid;
    upload.render({
        elem: uploadBtn //绑定元素
        ,url:  contextPath+"/files/?tablename="+tablename+"&ownerid="+ownerid+"&fileid="+ (fileid = uuid()) //上传接口
        ,accept:'file'
        ,done: function(res){
            //上传完毕回调
            if(res.message == "上传成功"){

                if($("#"+filename).val() != ""){
                    console.log(fileid);
                    $.ajax({
                        url: contextPath+"/files/"+$("#"+filename).val(),
                        type: "DELETE",
                        contentType:"application/json;charset=utf-8",
                        dataType:"json",
                        success: function(res) {
                            if(res.message == "删除成功！"){
                                $(uploadBtn).hide();
                                $(lookBtn).show();
                                $(delBtn).show();
                                $(delBtn).attr("fileid",fileid);
                                $(lookBtn).attr("fileid",fileid);
                                $("#"+filename).val(fileid);
                               }
                            }
                    });
                    layer.msg("上传成功！");
                }else{
                    console.log(fileid);
                    $(uploadBtn).hide();
                    $(lookBtn).show();
                    $(delBtn).show();
                    $(delBtn).attr("fileid",fileid);
                    $(lookBtn).attr("fileid",fileid);
                    $("#"+filename).val(fileid);
                    layer.msg("上传成功！");
                }


            }
        }


    });
}
function lookFile($,layer,filename) {
    var lookBtn = "#look"+filename+"Btn";


    $(lookBtn).on('click',function () {
        if($("+lookBtn+").attr("fileid")){
            fileid = $(lookBtn).attr("fileid");
        }else {
            fileid = $("#"+filename).val();
        }
         console.log(fileid);
        $.ajax({
            url: contextPath+"/files/"+fileid,
            type: "GET",
            contentType:"application/json;charset=utf-8",

            dataType:"json",
            success: function(res) {
                if(res){
                    console.log(res);
                    var src = '../files/'+ res.fileurl;

                    var json = {};
                    json.title = "";
                    json.id = 123;
                    json.start = 0;
                    json.data=[{"alt":"","pid":"","src":src,"thumb":src}];
                    console.log(json);
                    layer.photos({
                        photos: json
                        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                    });

                }else {
                    layer.msg("文件不存在！");
                }

            }

        });
    });

}

function checkFile($,fileid,filename) {
    var lookBtn = "#look"+filename+"Btn";
    var delBtn = "#del"+filename+"Btn";
    var uploadBtn = "#" +filename+"Btn";

    if(fileid == ""){
        $(uploadBtn).show();
    }else {
        $.ajax({
            url: contextPath+"/files/"+fileid,
            type: "GET",
            contentType:"application/json;charset=utf-8",
            dataType:"json",
            success: function(res) {
                if(res){

                    $(delBtn).attr("fileid",fileid);
                    $(lookBtn).attr("fileid",fileid);
                        $(lookBtn).show();
                        $(delBtn).show();
                }else {
                    $(uploadBtn).show();
                }

            }

        });
    }
}

function checkFileB($,fileid,filename,isOKdel,isOKUpdate) {
    var lookBtn = "#look"+filename+"Btn";
    var delBtn = "#del"+filename+"Btn";
    var uploadBtn = "#" +filename+"Btn";

    if(fileid == ""){
        if(isOKUpdate){
            $(uploadBtn).show();
        }else {
            $(uploadBtn).show();
            $(uploadBtn).attr("disabled","disabled");
            $(uploadBtn).addClass("layui-btn-disabled");
        }
    }else {
        $.ajax({
            url: contextPath+"/files/"+fileid,
            type: "GET",
            contentType:"application/json;charset=utf-8",
            dataType:"json",
            success: function(res) {
                if(res){

                    $(delBtn).attr("fileid",fileid);
                    $(lookBtn).attr("fileid",fileid);
                    $(lookBtn).show();

                    if(isOKdel){
                        $(delBtn).show();
                    }

                }else {
                    if(isOKUpdate){
                        $(uploadBtn).show();
                    }else {
                        $(uploadBtn).show();
                        $(uploadBtn).attr("disabled","disabled");
                        $(uploadBtn).addClass("layui-btn-disabled");
                    }

                }

            }

        });
    }
}

function delFile($,layer,filename) {

    var lookBtn = "#look"+filename+"Btn";
    var delBtn = "#del"+filename+"Btn";
    var uploadBtn = "#" +filename+"Btn";
    console.log(delBtn);
    console.log(filename);
    if($("#"+filename).val()!=""){
        $(delBtn).on('click',function () {
            console.log(filename);
            $.ajax({
                url: contextPath+"/files/"+$("#"+filename).val(),
                type: "DELETE",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    if(res.message == "删除成功！"){
                        $("#"+filename).val("");
                        $(uploadBtn).show();
                        $(lookBtn).hide();
                        $(delBtn).hide();
                        layer.msg(res.message);
                    }else if(res.message == "文件不存在！"){
                        $("#"+filename).val("");
                        $(uploadBtn).show();
                        $(lookBtn).hide();
                        $(delBtn).hide();
                        layer.msg(res.message+"请重新上传");
                    }
                }

            });
        });
    }else {
        $(delBtn).on('click',function () {
            console.log(filename);
            $.ajax({
                url: contextPath+"/files/"+$(delBtn).attr("fileid"),
                type: "DELETE",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    if(res.message == "删除成功！"){
                        $("#"+filename).val("");
                        $(uploadBtn).show();
                        $(lookBtn).hide();
                        $(delBtn).hide();
                        layer.msg(res.message);
                    }else if(res.message == "文件不存在！"){
                        $("#"+filename).val("");
                        $(uploadBtn).show();
                        $(lookBtn).hide();
                        $(delBtn).hide();
                        layer.msg(res.message+"请重新上传");
                    }
                }

            });
        });
    }

}

function getFormatDate(){
    var nowDate = new Date();
    var year = nowDate.getFullYear();
    var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    // var hour = nowDate.getHours()< 10 ? "0" + nowDate.getHours() : nowDate.getHours();
    // var minute = nowDate.getMinutes()< 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
    // var second = nowDate.getSeconds()< 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
    return year + "-" + month + "-" + date;
}

//传一个elem跟数组的 计算和
function getSumI($,elem,elems,sumElem) {
    $("#"+elem).blur(function(){
        //去空格
        $(this).val($.trim($(this).val()));
        //空取0
        $(this).val($(this).val() == ""?0:$(this).val());
        var pattern1 = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
        var pattern2 = /^-?[1-9]\d*$/;
        if(pattern1.test($(this).val()) ||pattern2.test($(this).val())){
            var sum=0;
            $.each(elems,function (i,e) {
                sum += parseFloat($("#"+e).val());
            });
            $("#"+sumElem).val(sum.toFixed(2));
        }else {
            layer.tips('请输入整数或者小数!', this);
        }
    });
}
//直接传一个数组的 计算和 素组 总数量控件id
function getSumII($,elems,sumElem){
    $.each(elems,function (i,e) {
        getSumI($,e,elems,sumElem);
    })
}
//校验 一个 elem 一个 正则

function judgment($,elem,pattern,message) {
    $("#"+elem).blur(function(){
        //去空格
        $(this).val($.trim($(this).val()));
        if(pattern.test($(this).val())){
        }else{
            layer.tips(message,this);
        }
    });
}

function delObjInArray($,obj,array) {
    console.log(obj,array);
    console.log($.inArray(obj,array));
    if($.inArray(obj,array) !=-1){
        array.splice($.inArray(obj,array),1);
    }
}
//校验 一堆
function judgments($,elems,pattern,message) {
    $.each(elems,function (i,e) {
        $("#"+e).blur(function(){
            //去空格
            $(this).val($.trim($(this).val()));
            if(pattern.test($(this).val())){
            }else{
                layer.tips(message,this);
            }
        });
    })

}

function yewuSearch(form,$) {
    //  渲染搜索 select
    form.on("select(khSearchKind)",function (data) {
        if(data.value == "khjc" ){
            $("#khSearchContent").empty();
            $.ajax({
                url: contextPath+"/cstmr",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#khSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].khjc+ "'>"+res.list[i].khjc+"</option>";
                        $("#khSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else if(data.value == "khzjm" ){
            $("#khSearchContent").empty();
            $.ajax({
                url: contextPath+"/cstmr",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#khSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].xlzjm+"'>"+res.list[i].xlzjm+"</option>";
                        $("#khSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else{
            $("#khSearchContent").empty();
        }

    });

    form.on("select(xlSearchKind)",function (data) {
        if(data.value == "xlmc" ){
            $("#xlSearchContent").empty();
            $.ajax({
                url: contextPath+"/road",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#xlSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].xlmc+ "'>"+res.list[i].xlmc+"</option>";
                        $("#xlSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else if(data.value == "xlzjm" ){
            $("#xlSearchContent").empty();
            $.ajax({
                url: contextPath+"/road",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#xlSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].xlzjm+"'>"+res.list[i].xlzjm+"</option>";
                        $("#xlSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else{
            $("#xlSearchContent").empty();
        }

    });

    form.on("select(khSearchKind)",function (data) {
        if(data.value == "khjc" ){
            $("#khSearchContent").empty();
            $.ajax({
                url: contextPath+"/cstmr",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#khSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].khjc+ "'>"+res.list[i].khjc+"</option>";
                        $("#khSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else if(data.value == "khzjm" ){
            $("#khSearchContent").empty();
            $.ajax({
                url: contextPath+"/cstmr",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#khSearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].khzjm+"'>"+res.list[i].khzjm+"</option>";
                        $("#khSearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else{
            $("#khSearchContent").empty();
        }

    });

    form.on("select(qySearchKind)",function (data) {
        if(data.value == "qymc" ){
            $("#qySearchContent").empty();
            $.ajax({
                url: contextPath+"/area",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#qySearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].qymc+ "'>"+res.list[i].qymc+"</option>";
                        $("#qySearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else if(data.value == "qyzjm" ){
            $("#qySearchContent").empty();
            $.ajax({
                url: contextPath+"/area",
                type: "GET",
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success: function(res) {
                    $("#qySearchContent").append("<option value=''>请选择</option>");
                    for(var i in res.list){
                        var option = "<option value='"+ res.list[i].zjm+"'>"+res.list[i].zjm+"</option>";
                        $("#qySearchContent").append(option);
                    };
                    form.render('select');
                }
            });
        }else{
            $("#qySearchContent").empty();
        }

    });
}